<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>家庭医生AI助手</title>
    <style>
        /* Minecraft风格样式 */
        @import url('https://fonts.googleapis.com/css2?family=Minecraft:wght@400;700&display=swap');
        
        :root {
            --minecraft-green: #4CAF50;
            --minecraft-dark-green: #388E3C;
            --minecraft-light-green: #66BB6A;
            --minecraft-gray: #333333;
            --minecraft-light-gray: #AAAAAA;
            --minecraft-dark-gray: #1A1A1A;
            --minecraft-beige: #F5F5DC;
            --minecraft-blue: #1E88E5;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            background-color: var(--minecraft-dark-gray);
            background-image: url('');
            color: var(--minecraft-beige);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            width: 100%;
            max-width: 800px;
            background-color: var(--minecraft-dark-gray);
            border: 3px solid var(--minecraft-light-gray);
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
        }
        
        .header {
            background-color: var(--minecraft-green);
            padding: 20px;
            text-align: center;
            border-bottom: 3px solid var(--minecraft-dark-green);
        }
        
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 2.5rem;
            font-weight: bold;
            letter-spacing: 1px;
        }
        
        .chat-container {
            height: 500px;
            display: flex;
            flex-direction: column;
        }
        
        .chat-history {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background-color: var(--minecraft-gray);
            background-image: url('');
        }
        
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 5px;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .user-message {
            background-color: var(--minecraft-blue);
            color: white;
            margin-left: auto;
            border: 2px solid var(--minecraft-beige);
        }
        
        .ai-message {
            background-color: var(--minecraft-light-gray);
            color: var(--minecraft-dark-gray);
            margin-right: auto;
            border: 2px solid var(--minecraft-beige);
        }
        
        .chat-input-container {
            padding: 20px;
            background-color: var(--minecraft-gray);
            border-top: 3px solid var(--minecraft-light-gray);
            display: flex;
            gap: 10px;
        }
        
        .chat-input {
            flex: 1;
            padding: 10px 15px;
            background-color: var(--minecraft-dark-gray);
            color: var(--minecraft-beige);
            border: 2px solid var(--minecraft-light-gray);
            border-radius: 5px;
            font-size: 16px;
            resize: none;
            height: 60px;
        }
        
        .send-button {
            padding: 10px 20px;
            background-color: var(--minecraft-green);
            color: white;
            border: 2px solid var(--minecraft-dark-green);
            border-radius: 5px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 100px;
        }
        
        .send-button:hover {
            background-color: var(--minecraft-dark-green);
            transform: translateY(-2px);
        }
        
        .send-button:active {
            transform: translateY(0);
        }
        
        .error-message {
            color: #ff6b6b;
            text-align: center;
            padding: 10px;
            background-color: rgba(255, 107, 107, 0.1);
            border: 1px solid #ff6b6b;
            border-radius: 5px;
            margin: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: var(--minecraft-light-green);
        }
        
        .loading::after {
            content: '';
            animation: dots 1.5s infinite;
        }
        
        @keyframes dots {
            0%, 20% { content: ''; }
            40% { content: '.'; }
            60% { content: '..'; }
            80%, 100% { content: '...'; }
        }
        
        /* 滚动条样式 */
        .chat-history::-webkit-scrollbar {
            width: 10px;
        }
        
        .chat-history::-webkit-scrollbar-track {
            background: var(--minecraft-dark-gray);
        }
        
        .chat-history::-webkit-scrollbar-thumb {
            background: var(--minecraft-light-gray);
            border-radius: 5px;
        }
        
        .chat-history::-webkit-scrollbar-thumb:hover {
            background: var(--minecraft-beige);
        }
        
        /* 响应式设计 */
        @media (max-width: 600px) {
            .header h1 {
                font-size: 1.8rem;
            }
            
            .chat-container {
                height: 400px;
            }
            
            .message {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>家庭医生AI助手</h1>
        </div>
        <div class="chat-container">
            <div id="chat-history" class="chat-history">
                <div class="ai-message message">
                    您好，我是AI家医助手。作为您的专属健康顾问，我态度友好、礼貌且言辞简洁。请问有什么可以帮您？
                </div>
            </div>
            <div class="chat-input-container">
                <textarea id="chat-input" class="chat-input" placeholder="请输入您的问题..."></textarea>
                <button id="send-button" class="send-button">发送</button>
            </div>
        </div>
    </div>
    
    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            const chatHistory = document.getElementById('chat-history');
            const chatInput = document.getElementById('chat-input');
            const sendButton = document.getElementById('send-button');
            
            // 生成唯一的memoryId（使用时间戳和随机数）
            let memoryId = Date.now() + Math.floor(Math.random() * 1000);
            
            // 发送消息函数
            function sendMessage() {
                const message = chatInput.value.trim();
                if (!message) return;
                
                // 添加用户消息到聊天记录
                const userMessageElement = document.createElement('div');
                userMessageElement.className = 'user-message message';
                userMessageElement.textContent = message;
                chatHistory.appendChild(userMessageElement);
                
                // 清空输入框
                chatInput.value = '';
                
                // 添加"正在输入"提示
                const loadingElement = document.createElement('div');
                loadingElement.className = 'ai-message message loading';
                loadingElement.textContent = 'AI正在回复';
                chatHistory.appendChild(loadingElement);
                
                // 滚动到底部
                chatHistory.scrollTop = chatHistory.scrollHeight;
                
                // 发送请求到后端API
                fetch('/doctor/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        memoryId: memoryId,
                        message: message
                    })
                })
                .then(response => {
                    // 移除"正在输入"提示
                    chatHistory.removeChild(loadingElement);
                    
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }
                    
                    // 处理流式响应
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let aiMessageElement = null;
                    let accumulatedText = '';
                    
                    function readStream() {
                        reader.read().then(({ done, value }) => {
                            if (done) {
                                return;
                            }
                            
                            // 解码接收到的字节
                            const chunk = decoder.decode(value, { stream: true });
                            accumulatedText += chunk;
                            
                            // 如果是第一次接收到数据，创建AI消息元素
                            if (!aiMessageElement) {
                                aiMessageElement = document.createElement('div');
                                aiMessageElement.className = 'ai-message message';
                                chatHistory.appendChild(aiMessageElement);
                            }
                            
                            // 更新消息内容
                            aiMessageElement.textContent = accumulatedText;
                            
                            // 滚动到底部
                            chatHistory.scrollTop = chatHistory.scrollHeight;
                            
                            // 继续读取流
                            readStream();
                        }).catch(error => {
                            console.error('读取流错误:', error);
                            showError('读取响应时发生错误');
                        });
                    }
                    
                    // 开始读取流
                    readStream();
                })
                .catch(error => {
                    console.error('发送请求错误:', error);
                    showError('发送请求时发生错误');
                });
            }
            
            // 显示错误信息
            function showError(message) {
                const errorElement = document.createElement('div');
                errorElement.className = 'error-message';
                errorElement.textContent = message;
                chatHistory.appendChild(errorElement);
                chatHistory.scrollTop = chatHistory.scrollHeight;
                
                // 3秒后自动移除错误信息
                setTimeout(() => {
                    if (chatHistory.contains(errorElement)) {
                        chatHistory.removeChild(errorElement);
                    }
                }, 3000);
            }
            
            // 发送按钮点击事件
            sendButton.addEventListener('click', sendMessage);
            
            // 输入框按Enter发送消息（不按Shift）
            chatInput.addEventListener('keydown', function(event) {
                if (event.key === 'Enter' && !event.shiftKey) {
                    event.preventDefault();
                    sendMessage();
                }
            });
        });
    </script>
</body>
</html>